#ifndef HTTPCLIENT_H
#define HTTPCLIENT_H

#include <QObject>
#include <QString>
#include <qfuture.h>
#include <QFutureWatcher>


struct DefHttpResult{
    DefHttpResult()
        :status_code{},response{},error{}
    {}
    DefHttpResult(int code,const QString& response,const QString& err)
        :status_code{code},response{response},error{err}
    {}
    int status_code{};
    QString response{};
    QString error{};
};

class HttpClient : public QObject
{
    Q_OBJECT
signals:
    void signal_get_finished(const DefHttpResult&result);
    void signal_post_finished(const DefHttpResult& result);
private slots:
    void OnOperateFinished();
public:
    explicit HttpClient(QObject *parent = nullptr);
    ~HttpClient();

    // HTTP GET 请求
    DefHttpResult httpGet(const QString& url);

    // HTTP POST 请求
    DefHttpResult httpPost(const QString& url, const QByteArray& postData);

    // 设置超时时间（秒）
    void setTimeout(long timeout);

    // 设置 User-Agent
    void setUserAgent(const QString& userAgent);

    void HttpGetAsync(const QString& url);

    void HttpPostAsync(const QString& url,const QByteArray& post_data);

private:
    static size_t writeCallback(void* contents, size_t size, size_t nmemb, void* userp);
private:
    long m_timeout;
    QString m_userAgent;
    QFutureWatcher<DefHttpResult>*m_get_watcher{};
    QFutureWatcher<DefHttpResult>*m_post_watcher{};
    DefHttpResult m_result{};
    QString m_response{};
};

#endif // HTTPCLIENT_H
